package com.ybbase.framework.config.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ybbase.framework.common.constant.ConfigConstant;
import com.ybbase.framework.model.po.system.Organization;
import com.ybbase.framework.model.po.system.Permission;
import com.ybbase.framework.model.po.system.Role;
import com.ybbase.framework.model.po.system.User;
import com.ybbase.framework.service.system.OrganizationService;
import com.ybbase.framework.service.system.PermissionService;
import com.ybbase.framework.service.system.RoleService;
import com.ybbase.framework.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class DbShiroRealm extends AuthorizingRealm {

    private final Logger log = LoggerFactory.getLogger(DbShiroRealm.class);
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private OrganizationService organizationService;

    public DbShiroRealm(UserService userService) {
        this.userService = userService;
        this.setCredentialsMatcher(new HashedCredentialsMatcher(Sha256Hash.ALGORITHM_NAME));
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userpasswordToken = (UsernamePasswordToken) token;
        String username = userpasswordToken.getUsername();
        User user = new User();
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(User::getLoginName, username);
            queryWrapper.lambda().eq(User::getDelFlag, 0);
            user = userService.getOne(queryWrapper);
            List<Organization> list = organizationService.getOrgListByUserId(user.getId());
            if (list!=null&&!list.isEmpty()){
                user.setOrganId(list.get(0).getId());
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        if (user == null) {
            throw new AuthenticationException("用户名或者密码错误");
        }
        return new SimpleAuthenticationInfo(user, user.getLoginName(), ByteSource.Util.bytes(ConfigConstant.ENCRYPT_SALT), ConfigConstant.DB_REALM);
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principals.getPrimaryPrincipal();
        List<String> roles = new ArrayList<>();
        List<String> rights = new ArrayList<>();
        List<Role> sysRoleList = new ArrayList<>();
        List<Permission> rightList = new ArrayList<>();
        if (user.getRoleList() != null && user.getRoleList().size() > 0) {
            sysRoleList = user.getRoleList();
        } else {
            try {
                sysRoleList = roleService.getRoleListByUserId(Integer.parseInt(user.getId() + ""));
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }
        String roleIds = "";
        for (Role role : sysRoleList) {
            roles.add(role.getId() + "");
            roleIds = "'" + role.getId() + "',";
        }
        if (roles != null) {
            simpleAuthorizationInfo.addRoles(roles);
        }
        if (!"".equals(roleIds)) {
            try {
                rightList = permissionService.getPermissionInRoleIds(roleIds);
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }
        if (rightList.size() > 0) {
            rightList.forEach(right -> rights.add(right.getId() + ""));
            simpleAuthorizationInfo.addStringPermissions(rights);
        }
        return simpleAuthorizationInfo;
    }


}
